package com.br.unisal.library.business;



import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.br.unisal.library.exception.NullValueException;
import com.br.unisal.library.util.Criteria;

/*
 * This class generate stub data to library
 */
public class LibraryBooks {
	
	private static final int NUMBER_OF_LIBRARY_BOOKS = 10;
	private String rootBookName = "Book";
	private Map<Identifier, Book> identifierByBookMap ;
	
	public LibraryBooks() throws IllegalArgumentException, NullValueException {
		createBookMap();
	}

	private void createBookMap() throws IllegalArgumentException, NullValueException {
		identifierByBookMap = new HashMap<Identifier, Book>();
		for(int index = 0; index < NUMBER_OF_LIBRARY_BOOKS; index++) {
			Identifier identificator = createIdentifier();
			Book book = createBook(index);
			book.setIdentificator(identificator);
			identifierByBookMap .put(identificator, book);		
		}
	}

	private Book createBook(int index) throws IllegalArgumentException, NullValueException {
		String bookName = rootBookName + index;
		Book book = new Book(bookName);
		return book;
	}

	private Identifier createIdentifier() {
		Identifier identifier =  new Identifier();
		return identifier;
	}

	public Book getBook(Criteria criterion, String parameter) {
		Book book = null;

		switch (criterion) {
		case BOOK_NAME:
			book = getBookByName(parameter);
			break;
		case IDENTIFIER:
			book = getBookByIdentifier(parameter);
			break;
		}

		return book;
	}

	private Book getBookByIdentifier(String parameter) {
		Book book = null;
		Set<Identifier> identifierSet = identifierByBookMap.keySet();
		for(Identifier identifier : identifierSet) {
			if(identifier.equals(parameter)) {
				book = identifierByBookMap.get(identifier);
			}
		}
		return book;	
	}

	private Book getBookByName(String parameter) {
		Book book = null;
		Collection<Book> books = identifierByBookMap.values();
		for(Book bookItem : books) {
			String bookName = bookItem.getBookName();
			if(bookName.equalsIgnoreCase(parameter)) {
				book = bookItem;
			}
		}
		return book;
	}
}
